package model

import (
	"errors"
	"github.com/jinzhu/gorm"
)

var (
	ErrUserRoleNotFound = errors.New("无法找到用户的角色信息，可能此用户还未被指定角色")
)

type (
	UserRoleRelations []*UserRole

	UserRole struct {
		Model
		UserID uint `json:"user_id" gorm:"column:user_id;index;not null;"`
		RoleID uint `json:"role_id" gorm:"column:role_id;index;not null;"`
	}
)

func DeleteUserRoleByUserID(userID int, tx *gorm.DB) error {
	if err := tx.Where("user_id = ?", userID).Delete(&UserRole{}).Error; err != nil {
		return err
	}

	return nil
}

func GetUserRoleWithUserID(userID int) (*UserRole, error) {
	userRole := new(UserRole)

	if err := db.Model(userRole).Where("user_id = ?", userID).Find(userRole).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, ErrUserRoleNotFound
		} else {
			return nil, err
		}
	}

	return userRole, nil
}

func UpdateUserRoleWithUserID(roleId uint, userID uint) error {
	userRole := new(UserRole)

	if err := db.Model(userRole).Where("user_id = ?", userID).Find(userRole).Updates(UserRole{RoleID: roleId}).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return ErrUserRoleNotFound
		} else {
			return err
		}
	}

	return nil
}

func GetUserRoleRelationsWithRoleID(roleID int) (UserRoleRelations, error) {
	rel := make([]*UserRole, 0)
	if err := db.Model(&UserRole{}).Where("role_id = ?", roleID).Find(&rel).Error; err != nil {
		return nil, err
	}
	return rel, nil
}

func GetAllUserRoleRelations() (UserRoleRelations, error) {
	rel := make([]*UserRole, 0)
	if err := db.Model(&UserRole{}).Find(&rel).Error; err != nil {
		return nil, err
	}
	return rel, nil
}

func (rel UserRoleRelations) ToMapUserIDAsKey() map[uint][]*UserRole {
	m := make(map[uint][]*UserRole)
	for _, userRole := range rel {
		m[userRole.UserID] = append(m[userRole.UserID], userRole)
	}
	return m
}
